var flowCountDayRatio,userFlowRatio;
var tipsIndex = 0;
$(function(){
	var winWidth = $(window).width();
	var winHeight = $(window).height();
	var jkjcWidth = $(".jkjc-module").parent("div").width() - 16 ;
	$(".jkjc-module").width( jkjcWidth * 0.6 );
	$(".ptyj-module").width( jkjcWidth * 0.4 );
	$(".tyjr-module").width( jkjcWidth * 0.5 );
	$(".sjk-module").width( jkjcWidth * 0.25 - 8);
	$(".redis-module").width( jkjcWidth * 0.25 - 8 );
	$(".tjtb-module").height(winHeight - 47 - $(".jkjc-module").height() - $(".tj-module").height() );
	
	$(".tj-module:odd").css("background-color","#9bceee");
	$(".tyjr-module .tyjrjd-item:first").css("padding","0px 10px 0px 0px");
	$(".tyjr-module .tyjrjd-item:last,.esbjq-module .tyjrjd-item:last,.fsdpjq-module .tyjrjd-item:last").css("border-right","none");
	
	Highcharts.setOptions({
        global: {
            useUTC: false
        }
    });
	
	//ESB集群和FSDP集群鼠标经过显示信息事件

	$("a[name='nodePoint']").mouseover(function(){
		
		var tips = "节点："+$(this).attr("nodeName");
		var remark = $(this).attr("remark");
		if(remark!="" && remark != undefined){
			tips += "</br>note："+remark;
		}
		tipsIndex = apexLayer.Tips({
			message:tips,
			more:false,
			guide:1,
			object:this,
			time:0
		});
	});
	
	$("a[name='nodePoint']").mouseout(function(){
		if(tipsIndex!=0)
			apexLayer.CloseIndex(tipsIndex);
	});
	$("#redisStatusPoint").mouseover(function(){
		
		var tips = $(this).attr("redisIp")+":" +$(this).attr("redisPort");
		tipsIndex = apexLayer.Tips({
			message:tips,
			more:false,
			guide:1,
			object:this,
			time:0
		});
	});
	
	$("#redisStatusPoint").mouseout(function(){
		if(tipsIndex!=0)
			apexLayer.CloseIndex(tipsIndex);
	});
	$("#mysqlStatusPoint").mouseover(function(){
		var dbUrl = $(this).attr("dbUrl").replace("?useUnicode=true&characterEncoding=utf-8","").replace("jdbc:mysql://","");
		var dbIp = dbUrl.split("/")[0];
		var dbBase = dbUrl.split("/")[1];
		var tips = "dbIp:"+dbIp+"<br>dataBase:"+dbBase+"<br>User:"+$(this).attr("dbUser") +"<br>Password:"+$(this).attr("dbPassword");
		tipsIndex = apexLayer.Tips({
			message:tips,
			more:false,
			guide:1,
			object:this,
			time:0
		});
	});
	
	$("#mysqlStatusPoint").mouseout(function(){
		if(tipsIndex!=0)
			apexLayer.CloseIndex(tipsIndex);
	});

	$("#onlineUserArea").click(function(){
		loadOnLineUsers();
	});
	$("#serviceCountArea").click(function(){
		loadServiceCount();
	});
	
	$("a[name='nodePoint']").click(function(){
		var nodeId = $(this).attr("nodeId");
		var nodeType = $(this).attr("nodeType");
		loadNodeView(nodeId,nodeType);
	});
	//刷新ESB、FSDP集群的状态
	refleshNodeData();
	refleshOnlineUserCount();
	refleshUaNodeStatus();
	refleshRedisStatus();
	refleshMysqlStatus();
	var task = setInterval(function(){  
		refleshNodeData();
		refleshUaNodeStatus();
		refleshRedisStatus();
		refleshMysqlStatus();
	},5000);  
	var task1 = setInterval(function(){  
		refleshOnlineUserCount();
	},30000);  
	
	initFlowCountDayChart();
	initUserFlowChart();
	loadFlowCountDay();
	loadUserFlow();
})

function showUaNodeInfo(obj) {
    var tips = $(obj).attr("nodeId")+"["+$(obj).attr("netIp")+":"+$(obj).attr("netPort")+"]";
    tipsIndex = apexLayer.Tips({
        message:tips,
        more:false,
        guide:1,
        object:$(obj),
        time:0
    });
}
function  closeIndexTips() {
    if(tipsIndex!=0)
        apexLayer.CloseIndex(tipsIndex);
}
function loadNodeView(nodeId,nodeType){
	apexLayer.OpenFrame({
		title:'节点['+nodeId+']详情',
		width:$(window).width()*0.97,
		height:$(window).height()*0.97,
		type:2,
		maxmin:true,
		closeBtn:1,
		scrollbar:false,
		content:contextPath+"/console/monitor/nodeView?nodeId="+nodeId+"&nodeType="+nodeType
		
	});
}
function loadOnLineUsers(){
 		
	apexLayer.OpenFrame({
		title:'用户会话',
		width:750,
		height:400,
		type:2,
		maxmin:true,
		closeBtn:1,
		scrollbar:false,
		content:contextPath+"/console/esbUserSession/queryOnLineUsers"
		
	});
}
function loadServiceCount(){
		
		apexLayer.OpenFrame({
			title:'服务调用统计',
			width:850,
			height:550,
			type:2,
			maxmin:true,
			closeBtn:1,
			scrollbar:false,
			content:contextPath+"/console/monitor/serviceCount"
			
		});
	}

//刷新ESB、FSDP集群的状态
function refleshNodeData(){
	var nodeStr = '',nodeTypeStr = '';
	$("a[name='nodePoint']").each(function(index){
		var nodeId = $(this).attr("nodeId");
		var nodeType = $(this).attr("nodeType");
		if(nodeId!=null && nodeId!=undefined && nodeType!=null && nodeType!=undefined){
			nodeStr += nodeId +",";
			nodeTypeStr += nodeType +",";
		}
	});
	getMonitorDataByNodeId(nodeStr,nodeTypeStr)
}

function getMonitorDataByNodeId(nodeStr,nodeTypeStr){
	Ajax({
		url: contextPath+"/console/monitor/queryNodeDataByNodeId",
		isMask : false,
		timeout:0,
		data: {
			nodeStr: nodeStr,
			nodeTypeStr: nodeTypeStr
		},
		success: function (data) {
			if(data.code>0){
				var records = data.records;
				for(var i=0;i<records.length;i++){
					var row = records[i];
					var nodeId = row.nodeId;
					var nodeType = row.nodeType;
					var obj = $("#"+nodeType+"_"+nodeId);
					$(obj).attr("remark",row.note);
					$(obj).attr("nodeName",row.nodeName);
					$(obj).attr("nodeId",row.nodeId);
					var remark = row.note==undefined?"":row.note;
					var src = contextPath+'/images/console/green-pic.png';
					var warningSrc = contextPath+'/images/console/orange-pic.png';
					if(row.code>0){
						
						if(row.diskInfo.diskWarning==1){
							src = warningSrc;
							remark += "<br>硬盘使用率达到预警值!";
						}
						if(row.cpuWarning==1){
							src = warningSrc;
							remark += "<br>cpu使用率达到预警值!";
						}
						if(row.memoryWarning==1){
							src = warningSrc;
							remark += "<br>内存使用率达到预警值!";
						}
						$("#img_"+nodeId).attr("src",src);
 						$(obj).attr("remark",remark);
					}else{
						$("#img_"+nodeId).attr("src",contextPath+'/images/console/red-pic.png')
					}
				}
			}
		}
	});
	
}

function refleshUaNodeStatus(){
	Ajax({
		url: contextPath+"/console/monitor/uaNodeStatus",
		isMask : false,
		timeout:0,
		data: {
		},
		success: function (data) {
			if(data.code>0 && data.count>0){
				var records = data.records;
				var content = '';
				for(var i = 0;i<records.length;i++){
					var nodeId = records[i].nodeId;
					var netIp = records[i].netIp;
					var netPort = records[i].netPort;
					var running = records[i].running;
					var status = records[i].status;
					var uaFlowCount = records[i].flowCount;
					if(status==1){
						content += '<a class="tyjrjd-item" onmouseover="showUaNodeInfo(this)" onmouseout="closeIndexTips()" name="uaNodePoint" nodeId="'+nodeId+'" netIp="'+netIp+'" netPort="'+netPort+'">';
						if(running){
							content += '<span class="ptzt-pic"><img src="'+contextPath+'/images/console/green-pic.png" width="14" height="14" /></span><br />';
						}else{
							content += '<span class="ptzt-pic"><img src="'+contextPath+'/images/console/red-pic.png" width="14" height="14" /></span><br />';
						}
						content += '<span class="tyjrjd-ll"><font>'+uaFlowCount+'</font>次</span>';
						content += '</a>';
					}
					
				}
				$("#uaNodeContainer").find("a").remove();
				$("#uaNodeContainer").append(content);
			}else{
				apexLayer.Warn("暂无统一接入节点");
			}
		}
	});
}
function refleshRedisStatus(){
	Ajax({
		url: contextPath+"/console/monitor/redisStatus",
		isMask : false,
		timeout:0,
		data: {
		},
		success: function (data) {
			if(data.redisStatus==1){
				$("#redisStatusPoint").attr("src",contextPath+'/images/console/green-pic.png');
			}else{
				$("#redisStatusPoint").attr("src",contextPath+'/images/console/red-pic.png');
			}
			$("#redisStatusPoint").attr("redisIp",data.redisIp);
			$("#redisStatusPoint").attr("redisPort",data.redisPort);
		}
	});
}
function refleshMysqlStatus(){
	Ajax({
		url: contextPath+"/console/monitor/mysqlStatus",
		isMask : false,
		timeout:0,
		data: {
		},
		success: function (data) {
			if(data.mysqlStatus==1){
				$("#mysqlStatusPoint").attr("src",contextPath+'/images/console/green-pic.png');
			}else{
				$("#mysqlStatusPoint").attr("src",contextPath+'/images/console/red-pic.png');
			}
			
			$("#mysqlStatusPoint").attr("dbUrl",data.dbUrl);
			$("#mysqlStatusPoint").attr("dbUser",data.dbUser);
			$("#mysqlStatusPoint").attr("dbPassword",data.dbPassword);
		}
	});
}
function refleshOnlineUserCount(){
	Ajax({
		url: contextPath+"/console/monitor/onlineUserCount",
		isMask : false,
		timeout:0,
		data: {
		},
		success: function (data) {
			$("#onlineUserCount").text(data.total);
		}
	});
}
var flowCountDayChar,userFlowCharts;
function loadFlowCountDay(){
	Ajax({
		url: contextPath+"/console/monitor/flowCountDay",
		isMask : true,
		data: {
			loginId:$("#esbUser").val()==undefined?"":$("#esbUser").val()
		},
		success: function (data) {
			$("#flowDayCount").text(data.total);
			flowCountDayRatio.series[0].data=data.yArray;
			flowCountDayChar = new Highcharts.Chart(flowCountDayRatio);
			var title_text = '';
			if($("#esbUser").val()!='' && $("#esbUser").val()!=undefined){
				title_text += '['+$("#esbUser").val()+']';
			}
			title_text += '当天服务流量（24小时）:'+data.total+'笔';
			var title = {
				    text:title_text
				};
			flowCountDayChar.setTitle(title,true);
		}
	});
}

function loadUserFlow(){
	
	Ajax({
		url: contextPath+"/console/monitor/userFlowCount",
		isMask : true,
		data: {
		},
		success: function (data) {
			userFlowRatio.series=data.yArray;
			userFlowCharts = new Highcharts.Chart(userFlowRatio);
		}
	});
}

function initFlowCountDayChart(){
	var xtext = [];
	flowCountDayRatio={
			credits:{
				enabled:false // 禁用版权信息
			},
			chart: {
				type: 'column',
				renderTo:'container_flowCount_day',
				animation: Highcharts.svg, // don't animate in old IE
				marginRight: 10,
				events: {
					load: function () {
						var series = this.series[0];
						setInterval(function () {
							Ajax({
								url: contextPath+"/console/monitor/flowCountDay",
								isMask : false,
								data: {
									loginId:$("#esbUser").val()==undefined?"":$("#esbUser").val()
								},
								success: function (result) {
									xtext = result.xArray;
									series.setData(result.yArray);
									var title_text = '';
									$("#flowDayCount").text(result.total);
					    			if($("#esbUser").val()!='' && $("#esbUser").val()!=undefined){
					    				title_text += '['+$("#esbUser").val()+']';
					    			}
					    			title_text += '当天服务流量（24小时）:'+result.total+'笔';
					    			var title = {
					    				    text:title_text
					    				};
					    			flowCountDayChar.setTitle(title,true);
								}
							});
						}, 5000);
					}
				}
			},
			title: {
				text: '当天服务流量（24小时）'
			},
			xAxis: {
				categories:xtext,
			    tickInterval: 2
			},
			yAxis: {
				title: {
					text: '服务请求流量(笔)'
				},
				min:0,
				allowDecimals:false,
				plotLines: [{
					value: 0,
					width: 1,
					color: '#808080'
				}]
			},
			tooltip: {
				formatter: function () {
					return this.x+'时服务请求流量为：' + this.y +'笔';
				}
			},
			legend: {
				enabled: false
			},
			exporting: {
				enabled: false
			},
			series: [{
				name: '服务数'
			}]
	};
}



function initUserFlowChart(){
	var xtext = [];
	userFlowRatio={
			credits:{
				enabled:false // 禁用版权信息
			},
			chart: {
				type: 'area',
				renderTo:'container_userFlow_day',
				animation: Highcharts.svg, // don't animate in old IE
				marginRight: 10,
				events: {
					load: function () {
						var series = this.series;
						setInterval(function () {
							Ajax({
								url: contextPath+"/console/monitor/userFlowCount",
								isMask : false,
								data: {
								},
								success: function (result) {
									xtext = result.xArray;
									var yArray = result.yArray;
									for(var i = 0;i<series.length;i++){
										for(var j = 0;j<yArray.length;j++){
											var name = yArray[j].name;
											if(series[i].name==name){
												series[i].setData(yArray[j].data);
											}
										}
									}
								}
							});
						}, 5000);
					}
				}
				
			},
			legend: {
				enabled: true
			},
			exporting: {
				enabled: false
			},
			title: {
	            text: '用户流量'
	        },
	        xAxis: {
	            categories: xtext,
	            tickmarkPlacement: 'on',
	            tickInterval: 2,
	            title: {
	                enabled: false
	            }
	        },
	        yAxis: {
	            title: {
	                text: '用户当天流量（笔）'
	            },
	            min:0,
				allowDecimals:false,
				plotLines: [{
					value: 0,
					width: 1,
					color: '#808080'
				}],
	            labels: {
	                formatter: function () {
	                    return this.value;
	                }
	            }
	        },
	        tooltip: {
	            shared: true,
	            valueSuffix: ' 笔'
	        },
	        plotOptions: {
	            area: {
	                stacking: 'normal',
	                lineColor: '#666666',
	                lineWidth: 0,
	                marker: {
	                    lineWidth: 0,
	                    lineColor: '#666666'
	                }
	            }
	        },
	        series: []
	};
}